package zozopo.user.dialog;

import java.io.IOException;
import java.sql.Connection;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import zozopo.comm.Validate;
import zozopo.database.BusiDatabaseManager;
import zozopo.database.DatabaseManager;
import zozopo.log.operations.UserLoginLogOS;
import zozopo.log.operations.UserLoginLogTB;
import zozopo.user.operations.TokenOS;
import zozopo.user.operations.TokenTB;
import zozopo.user.operations.UserOS;
import zozopo.user.operations.UserTB;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

public class LoginDialogAction extends ActionSupport implements Action,SessionAware,ServletRequestAware,ServletResponseAware{
	
	//传入参数
	private String account;  //账号,可以用email 或用户
	private String password;
	
	//传出参数
	private String responseText;
	private Boolean isSuccess=true;
	
	
	
	
	public String execute(){
		DatabaseManager databaseManager = new BusiDatabaseManager();
		Connection conn = null;
		
		UserTB user = null;
		
		responseText = getValidateInfo();
		
		if(responseText==null){
			try{
				conn = databaseManager.getConnection();
				
				//如果需要高效率需要整合成存储过程 .
				UserOS userOS = new UserOS(conn);	
				TokenOS tokenOS = new TokenOS(conn);
				UserLoginLogOS userLoginLogOS = new UserLoginLogOS(conn);
				
				
				TokenTB token = new TokenTB();
				//日志
				UserLoginLogTB userLoginLog = new UserLoginLogTB();
				userLoginLog.setType("界面");
				userLoginLog.setAccount(account);
				userLoginLog.setIp(request.getRemoteAddr());
				
				
				if(Validate.isEmail(account)){    // 如果是EMAIL
					user = userOS.getUserInfoByEmail(account);
				}else{
					user = userOS.getUserInfoByName(account);
				}
				
				
				
				//写入登陆日志
				userLoginLog.setIswrong(false);
				userLoginLogOS.insert(userLoginLog);
				
				UserLoginLogTB  lastLoginLog= userLoginLogOS.getNewLoginInfo(account);//获取上次次登陆信息
				
				
				
				session.put("userInfo", user);
				session.put("loginLog", lastLoginLog);
				
				
				
				String tokenStr = request.getSession().getId();
				token.setOpenid(user.getId_user()+"");
				token.setToken(tokenStr);
				token.setUsername(user.getName_user());
				
				
				Cookie cookie = new Cookie("SESSIONID", tokenStr);
				cookie.setMaxAge(24*60*60*90);   //秒
				response.addCookie(cookie);
				
				tokenOS.deleteByOpenid(user.getId_user()+"");//清空
				tokenOS.insert(token);
				
			}finally{
				if(conn != null){
					databaseManager.releaseConnection(conn);
				}
			}
			responseText = "登陆成功.";
		}
			
		
		
		
		try {
			
			response.getWriter().append("{\"responseText\":\"");
			response.getWriter().append(responseText);
			response.getWriter().append("\",\"isSuccess\":\"");
			response.getWriter().append(isSuccess.toString());
			response.getWriter().append("\"}");
			response.getWriter().flush();
			response.getWriter().close();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return NONE;
	}
	
	
	public String getValidateInfo() {
		
		
		if(account == null){
			isSuccess = false;
			responseText = "账号不能为空.";
			return responseText;
		}
		
		DatabaseManager databaseManager = new BusiDatabaseManager();
		Connection conn = null;
		
		try{
			conn = databaseManager.getConnection();
			
			//如果需要高效率需要整合成存储过程 .
			UserOS userOS = new UserOS(conn);	
			
			UserLoginLogOS userLoginLogOS = new UserLoginLogOS(conn);
			
			
		
			
			//日志
			UserLoginLogTB userLoginLog = new UserLoginLogTB();
			userLoginLog.setType("登陆框");
			userLoginLog.setAccount(account);
			userLoginLog.setIp(request.getRemoteAddr());
			
			
			if(!userLoginLogOS.isAccountSecurity(account)){// 如果超出输入密码错误次数.账号存在异常.
				isSuccess = false;
				responseText = "账号异常,存在安全问题.请稍后再输入";
				return responseText;
			}
			
			if(userLoginLogOS.isWorngOutOfTime(account)){// 如果超出输入密码错误次数.需要校验证码.
				isSuccess = false;
				responseText = "账号异常,存在安全问题.请进入登陆界面进行登陆.";	
				return responseText;
				
			}
			
			
			if(Validate.isEmail(account)){    // 如果是EMAIL
	
				
				if(account.length() > 320){
					isSuccess = false;
					responseText = "EMAIL长度不能大于320个字符.";	
					return responseText;
				}
				
				if(!userOS.isRealUserByEmail(account, password)){
					
					
					//写入错误的登陆日志
					userLoginLog.setIswrong(true);
					userLoginLogOS.insert(userLoginLog);
					
					//清空session valicode
					addFieldError("errormessage", getText("background.login.sign.wrong"));
					isSuccess = false;
					responseText = "登陆失败,用户名或密码错误,请检查后重新输入.";	
					return responseText;
				}
				
			}else{   //非EMAIL登陆
				if(!userOS.isRealUser(account, password)){
					//写入错误的登陆日志
					userLoginLog.setIswrong(true);
					userLoginLogOS.insert(userLoginLog);
					
					isSuccess = false;
					responseText = "登陆失败,用户名或密码错误,请检查后重新输入.";	
					return responseText;
				}
			}
			}finally{
				if(conn != null){
					databaseManager.releaseConnection(conn);
				}
			}
			
			return responseText;
			
	}
	

	
	private HttpServletRequest request;
	private HttpServletResponse response;
	private Map<Object, Object> session;

	public void setServletRequest(HttpServletRequest arg0) {
		// TODO Auto-generated method stub
		request = arg0;
	}

	public void setSession(Map arg0) {
		// TODO Auto-generated method stub
		session = arg0;
	}

	

	public void setServletResponse(HttpServletResponse arg0) {
		// TODO Auto-generated method stub
		response = arg0;
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=UTF-8");
	}


	public String getAccount() {
		return account;
	}


	public void setAccount(String account) {
		this.account = account;
	}


	public String getPassword() {
		return password;
	}


	public void setPassword(String password) {
		this.password = password;
	}
}
